# Maintainer: Mateusz Mikuła <mati865@gmail.com>

_realname=compiler-rt
_mingw_suff=mingw-w64-cross
pkgname=("${_mingw_suff}-${_realname}")
pkgver=11.0.0
pkgrel=5
pkgdesc="Compiler runtime libraries for cross clang"
arch=('i686' 'x86_64')
url="https://llvm.org"
license=('custom:Apache 2.0 with LLVM Exception')
depends=('clang')
makedepends=("cmake" "lld" "ninja" "${_mingw_suff}-clang-headers")
options=('!strip' 'staticlibs' '!emptydirs' '!buildflags')
_url=https://github.com/llvm/llvm-project/releases/download/llvmorg-${pkgver}
source=(${_url}/compiler-rt-${pkgver}.src.tar.xz{,.sig})
sha256sums=('374aff82ff573a449f9aabbd330a5d0a441181c535a3599996127378112db234'
            'SKIP')
validpgpkeys=('B6C8F98282B944E3B0D5C2530FC3042E345AD05D'  # Hans Wennborg, Google.
              '474E22316ABF4785A88C6E8EA2C794A986419D8A') # Tom Stellard

_targets="x86_64-w64-mingw32 i686-w64-mingw32"

prepare() {
  cd ${srcdir}
}

build() {
  for _target in ${_targets}; do
    cd "${srcdir}"
    case "${_target}" in
      x86_64*)
        _sizeof_void_p=8
        _llvmtarget=x86_64
        ;;
      i686*)
        _sizeof_void_p=4
        _llvmtarget=i386
        ;;
    esac

    [[ -d build-${_target} ]] && rm -rf build-${_target}
    mkdir build-${_target} && cd build-${_target}

    export CC="clang" CXX="clang++" AS="clang" AR="llvm-ar" RANLIB="llvm-ranlib" DLLTOOL="llvm-dlltool" LD="clang"
    export ASMFLAGS

    ASMFLAGS+=" -target ${_target} --sysroot=/opt/${_target}"
    CFLAGS+=" -target ${_target} --sysroot=/opt/${_target}"
    CPPFLAGS+=" -target ${_target} --sysroot=/opt/${_target}"
    CXXFLAGS+=" -target ${_target} --sysroot=/opt/${_target}"
    LDFLAGS+=" -target ${_target} --sysroot=/opt/${_target} -fuse-ld=lld"

    cmake \
      -G'Ninja' \
      -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_C_COMPILER_TARGET=${_llvmtarget}-windows-gnu \
      -DCMAKE_C_COMPILER_WORKS=ON \
      -DCMAKE_CXX_COMPILER_WORKS=ON \
      -DCMAKE_INSTALL_PREFIX=/usr \
      -DCMAKE_SIZEOF_VOID_P=${_sizeof_void_p} \
      -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib \
      -DCMAKE_SYSTEM_NAME=Windows \
      -DCOMPILER_RT_BUILD_LIBFUZZER=OFF \
      -DCOMPILER_RT_BUILD_PROFILE=OFF \
      -DCOMPILER_RT_BUILD_SANITIZERS=OFF \
      -DCOMPILER_RT_BUILD_XRAY=OFF \
      -DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON \
      -DCOMPILER_RT_USE_BUILTINS_LIBRARY=ON \
      ../${_realname}-${pkgver}.src

    ninja
  done
}

package() {
  # ninja install needs working compiler detection to find correct directory
  for _target in ${_targets}; do
    if [[ ${_target} == i?86* ]]; then
      _llvmtarget=i386
    else
      _llvmtarget=${_target%%-*}
    fi
    cd $srcdir/build-${_target}
    mkdir -p "${pkgdir}/usr/lib/clang/${pkgver}/lib/windows"
    cp "lib/windows/libclang_rt.builtins-${_llvmtarget}.a" "${pkgdir}/usr/lib/clang/${pkgver}/lib/windows"
  done
}
